package com.lsk.api;

import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.lsk.util.*;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 速消卡
 */
public class SXKService {

    final static String cardSubmitUrl="http://api.suxiaoka.cn/api/card/submitCard.do";

    final static String appId="1092680552";

    final static String signAppSert="g6t93viya7tpyde5qk5gf9hnti1tu5jc";

    final static  String desAppSert="x6hxc08es2fai7mng3abewuun27wi6nk";

    /**
     *  提交卡片
      * @param temp
     */
    public static void cardSubmit(Record temp){

        //提交 游戏卡话费卡

        try {

            String cardId = temp.getStr("id");

            Map<String, String> parameters = new HashMap<>();

            parameters.put("customerId", appId);

            String orderId = "SXKService" + DateUtil.getSdfTimes() + Tools.getRandomNum();

            parameters.put("orderId", orderId);

            ///产品编码
            String productCode=temp.getStr("productCode");

            String face = temp.getStr("feedbackValue");

            face=new DecimalFormat("######0").format(Double.valueOf(face));

            parameters.put("amount", face);//面值


            parameters.put("productCode",productCode);


            String feedbackId = temp.getStr("feedbackId");

            Record saleCardDiscount = Db.findFirst("select * from commodity_facevalue where id=?", feedbackId);


            parameters.put("userPrice", saleCardDiscount.getStr("saleCardDiscount"));

            String confiSql = "SELECT `value` from sys_config where element='domain'";

            String domain = Db.queryStr(confiSql);

            parameters.put("callbackURL", "http://" + domain.replace("http://", "")+"/mobile/sxkCallBack");//回调地址

            String inputCardNumber = temp.getStr("cardNumber");

            parameters.put("cardNumber", DES3Util.encryptToHex(desAppSert,inputCardNumber));

            String inputCardPassword = temp.getStr("cardPassword");

            parameters.put("cardPassword",  DES3Util.encryptToHex(desAppSert,inputCardPassword));

            Map<String, String> signMap = new HashMap<>();

            signMap = parameters;

            String sign = submitSign(signMap);

            parameters.put("sign", sign);//加密签名，加密原文请参考下面的加密拼接，MD5加密

            parameters.put("extendParams","");

            Double discount=saleCardDiscount.getDouble("saleCardDiscount")*100.00;//折扣金额

            parameters.put("discount",discount+"");

            Syslog.info("向速消卡推送参数为：" + JsonUtil.getJsonStr(parameters));

            System.out.println(JsonUtil.getJsonStr(parameters));

            String result = HttpKit.post(cardSubmitUrl, parameters,JsonUtil.getJsonStr(parameters));

            //System.out.println("*****************"+result);


            Syslog.info("速消卡推送结果为：" + result);

            temp.remove("code").set("createTime", new Date()).set("returnJson", result)
                    .remove("id").set("cardId", cardId).set("id", orderId);

            Record myData = new Record().set("id", orderId).set("cardId", cardId).set("classId", temp.getStr("classId")
            ).set("commodityId", temp.getStr("commodityId")).set("commodityName", temp.getStr("commodityName"))
                    .set("feedbackId", temp.getStr("feedbackId")).set("feedbackValue", temp.getStr("feedbackValue"))
                    .set("discount", saleCardDiscount.getStr("saleCardDiscount")).set("createTime", new Date()).set("returnCode", result)
                    .set("returnMsg", ApiReturn.getMsgByCode(result+"", "4"))
                    .set("returnJson", result).set("cardNumber", temp.getStr("cardNumber")).set("cardPassword", temp.getStr("cardPassword"))
                    .set("orderId", temp.getStr("orderId")).set("memberId", temp.getStr("memberId")).set("imgPath", temp.getStr("imgPath"))
                    .set("className", temp.getStr("className"));


            Db.save("card_send_logs", "id", myData);

            Record card = new Record().set("id", cardId).set("state", 2).set("msg", ApiReturn.getMsgByCode(result+"", "4"));

            Db.update("card", "id", card);


            if ("100026".equals(result)) {//提交成功

                 card = new Record().set("id", cardId).set("state",6).set("msg", ApiReturn.getMsgByCode(result, "4")+"（速销卡）");

                Db.update("card", "id", card);
//            }else if("18006".equals(result)){  //供货价格错误.设置为处理中
//
//                card = new Record().set("id", cardId).set("state", 2).set("msg",ApiReturn.getMsgByCode(result,"4"));
//
//                Db.update("card", "id", card);
//            }else{  //提交失败
//                 card = new Record().set("id", cardId).set("state", 3).set("msg",ApiReturn.getMsgByCode(result,"4"));
//
//                Db.update("card", "id", card);
           }


        } catch (Exception e) {

            Syslog.error("推送到速销卡，卡信息：" + temp.toJson());

            Syslog.error(e);

        }



    }

    /**
     * 提交签名
     *
     * @param parameters
     * @return
     */
    public static String submitSign(Map<String, String> parameters) {

        String orderId = parameters.get("orderId");

        String sign =appId +"&"+orderId +"&"+ parameters.get("productCode")+"&"
                +parameters.get("amount" ) +"&"+ parameters.get("cardNumber") +"&"+parameters.get("cardPassword" ) +"&"+ parameters.get("callbackURL")
                +"&"+ signAppSert;

        System.out.println(UtilUrlEncode.URLDecoderString(sign));

        sign = MD5.md5(UtilUrlEncode.URLDecoderString(sign));

        return sign;

    }

    /**
     * 提交签名
     *
     * @param parameters
     * @return
     */
    public static String submitSignRel(Map<String, String> parameters) {

        String orderId = parameters.get("orderId");

        String sign =appId +"&"+orderId +"&"+ parameters.get("productCode")+"&"
                +parameters.get("amount" ) +"&"+ parameters.get("cardNumber") +"&"
                +parameters.get("cardPassword" )
                +"&"+parameters.get("discount" )
                +"&"+ parameters.get("callbackURL")
                +"&"+parameters.get("effectTime" )
                +"&"+parameters.get("timestamp" )
                +"&"+ signAppSert;

        System.out.println(UtilUrlEncode.URLDecoderString(sign));

        sign = MD5.md5(UtilUrlEncode.URLDecoderString(sign));

        return sign;

    }



    /**
     *  提交加油卡
     * @param temp
     */
    public static void cardSubmitRefuel(Record temp){

        //提交 游戏卡话费卡

        try {

            String cardId = temp.getStr("id");

            Map<String, String> parameters = new HashMap<>();

            parameters.put("customerId", appId);

            String orderId = "SXKService" + DateUtil.getSdfTimes() + Tools.getRandomNum();

            parameters.put("orderId", orderId);

            ///产品编码
            String productCode=temp.getStr("productCode");

            String face = temp.getStr("feedbackValue");

            face=new DecimalFormat("######0").format(Double.valueOf(face));

            parameters.put("amount", face);//面值


            parameters.put("productCode",productCode);


            String feedbackId = temp.getStr("feedbackId");

            Record saleCardDiscount = Db.findFirst("select * from commodity_facevalue where id=?", feedbackId);


            parameters.put("userPrice", saleCardDiscount.getStr("saleCardDiscount"));

            String confiSql = "SELECT `value` from sys_config where element='domain'";

            String domain = Db.queryStr(confiSql);

            parameters.put("callbackURL", "http://" + domain.replace("http://", "")+"/mobile/sxkCallBack");//回调地址

            String inputCardNumber = temp.getStr("cardNumber");

            parameters.put("cardNumber", DES3Util.encryptToHex(desAppSert,inputCardNumber));

            String inputCardPassword = temp.getStr("cardPassword");

            parameters.put("cardPassword",  DES3Util.encryptToHex(desAppSert,inputCardPassword));


            Double discount=saleCardDiscount.getDouble("saleCardDiscount")*100.00;//折扣金额


            parameters.put("discount",discount+"");

            String effectTime=DateUtil.getAfterDay("3");//三天以后的日期

            parameters.put("effectTime",effectTime+"");

            String timestamp=System.currentTimeMillis()+"";

            parameters.put("timestamp",timestamp);



            Map<String, String> signMap = new HashMap<>();

            signMap = parameters;

            String sign = submitSignRel(signMap);

            parameters.put("sign", sign);//加密签名，加密原文请参考下面的加密拼接，MD5加密


            parameters.put("extendParams","");


            Syslog.info("向速消卡推送参数为：" + JsonUtil.getJsonStr(parameters));

            System.out.println(JsonUtil.getJsonStr(parameters));

            String cardUrl="http://api.suxiaoka.cn/api/hoil/submitCard.do";

            String result = HttpKit.post(cardUrl, parameters,JsonUtil.getJsonStr(parameters));

            //System.out.println("*****************"+result);


            Syslog.info("速消卡推送结果为：" + result);

            temp.remove("code").set("createTime", new Date()).set("returnJson", result)
                    .remove("id").set("cardId", cardId).set("id", orderId);

            Record myData = new Record().set("id", orderId).set("cardId", cardId).set("classId", temp.getStr("classId")
            ).set("commodityId", temp.getStr("commodityId")).set("commodityName", temp.getStr("commodityName"))
                    .set("feedbackId", temp.getStr("feedbackId")).set("feedbackValue", temp.getStr("feedbackValue"))
                    .set("discount", saleCardDiscount.getStr("saleCardDiscount")).set("createTime", new Date()).set("returnCode", result)
                    .set("returnMsg", ApiReturn.getMsgByCode(result+"", "4"))
                    .set("returnJson", result).set("cardNumber", temp.getStr("cardNumber")).set("cardPassword", temp.getStr("cardPassword"))
                    .set("orderId", temp.getStr("orderId")).set("memberId", temp.getStr("memberId")).set("imgPath", temp.getStr("imgPath"))
                    .set("className", temp.getStr("className"));


            Db.save("card_send_logs", "id", myData);

            Record card = new Record().set("id", cardId).set("state", 2).set("msg", ApiReturn.getMsgByCode(result+"", "4"));

            Db.update("card", "id", card);


            if ("100026".equals(result)) {//提交成功

                card = new Record().set("id", cardId).set("state",6).set("msg", ApiReturn.getMsgByCode(result, "4")+"（速销卡）");

                Db.update("card", "id", card);
//            }else if("18006".equals(result)){  //供货价格错误.设置为处理中
//
//                card = new Record().set("id", cardId).set("state", 2).set("msg",ApiReturn.getMsgByCode(result,"4"));
//
//                Db.update("card", "id", card);
//            }else{  //提交失败
//                 card = new Record().set("id", cardId).set("state", 3).set("msg",ApiReturn.getMsgByCode(result,"4"));
//
//                Db.update("card", "id", card);
            }


        } catch (Exception e) {

            Syslog.error("推送到速销卡，卡信息：" + temp.toJson());

            Syslog.error(e);

        }



    }

    public static void main(String[] strings){




    }


}
